using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Outpatient.ErrorCode;
using OutpatientApi.DTO;
using OutpatientApi.Methodimplementation.IServices;

namespace OutpatientApi.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ILogger<UserController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userService">用户服务</param>
        /// <param name="logger">日志记录器</param>
        public UserController(IUserService userService, ILogger<UserController> logger)
        {
            _userService = userService;
            _logger = logger;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginDto">登录参数</param>
        /// <returns>登录结果</returns>
        [HttpPost]
        public async Task<ApiResult<UserLoginResultDto>> Login([FromBody] UserLoginDto loginDto)
        {
            try
            {
                // 记录API调用日志
                _logger.LogInformation("用户登录API调用开始，用户名：{Username}", loginDto.Username);

                // 参数验证
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    
                    _logger.LogWarning("用户登录参数验证失败：{Errors}", string.Join(", ", errors));
                    return new ApiResult<UserLoginResultDto> { msg = "参数验证失败" };
                }

                // 调用服务层进行登录
                var result = await _userService.LoginAsync(loginDto);

                // 记录API调用结果日志
                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("用户登录API调用成功，用户ID：{UserId}", result.data?.UserId);
                }
                else
                {
                    _logger.LogWarning("用户登录API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                // 记录API调用异常日志
                _logger.LogError(ex, "用户登录API调用异常，用户名：{Username}", loginDto.Username);
                return new ApiResult<UserLoginResultDto> { msg = "登录过程中发生异常" };
            }
        }


        /// <summary>
        /// 健康检查接口
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet]
        public ApiResult<string> Health()
        {
            var result = new ApiResult<string>();
            result.success("OK", "用户服务正常运行");
            return result;
        }
    }
} 